<?php

namespace App\Http\Controllers\Source\Rong360;

use App\Constant\QueueKey;
use App\Constant\Rong360Enum;
use App\Constant\SmsTemplate;
use App\Events\UserLoanApplyEvent;
use App\Facades\CommonPlatformRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use App\Http\Controllers\Source\BaseController;
use App\Http\Requests\Frontend\V10\Loan\ApplyLoanRequest;
use App\Jobs\GetLoanResultJobQueue;
use App\Library\Source\Rong360\Rong360Request;
use App\Models\LoanApply;
use App\Models\SettingRepayRate;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Service\User;

/**
 * Class LoanRequestController
 * @package App\Http\Controllers\Source\Rong360
 */
class LoanRequestController extends BaseController
{

    use User;
    //
    /**
     * 审批结论
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author luwei
     * @date 2019-03-01 09:51
     */
    public function loanStatus(Request $request){
        $data = $this->initData($request);
        $orderNo = $data['order_no']??'258469037086236';
        $loan = UserLoanRequest::with('userGlobalStatus')->byTransId($orderNo)->first();
        if(!$loan){
            return r360fail('借款信息不存在！');
        }
        $global = $loan->userGlobalStatus;
        $status = $global->global_status ?? 0;

        switch ($status){
            case UserGlobal::STATUS_LOAN_REQUEST_FAILED:
                $data = [
                    'order_no' => $orderNo,
                    'conclusion' => Rong360Enum::CONCLUSION_FAILED,
                    'remark' => $loan->failed_reason,
                    'refuse_time' => $loan->failed_time
                ];
                break;
            case UserGlobal::STATUS_LOAN_REQUEST_SUCCESS:
                //todo deal logic
                $data = $this->dealLoanSuccess($orderNo,$loan);
                break;
            default:
                $data = [];
        }

        return r360Success($data);

    }

    /**
     * 审批结论通过数据
     * @param $orderNo
     * @param $loan
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @author luwei
     * @date 2019-03-01 09:50
     */
    protected function dealLoanSuccess($orderNo, $loan){
        $data = [
            'applyAmount' => $loan->actual_money,
            'period' => $loan->actually_period,
            'channel' => $loan->channel??''
        ];
        $periodAmount = UserLoanRequest::getCalculate($data);
//        dump($periodAmount);
        //todo 总还款金额
        $ret = [
            'order_no' => $orderNo,
            'conclusion' => Rong360Enum::CONCLUSION_SUCCESS,
            'approval_time' => $loan->credit_time,
            'amount_type' => 0,
            'approval_amount' => $loan->actual_money,
            'term_unit' => 2,
            'term_type' => 0,
            'approval_term' => $loan->actually_period,
            'receive_amount' => LoanApply::receiveMoney($loan),
            'period_amount' => $periodAmount['total_amount'],
//            'pay_amount' => ''
//            'remark'
        ];
        dd($ret);
    }


    /**
     * 审批确认接口
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @author cg
     * @date 2019-03-01 11:30
     */
    public function loanConfirm(Request $request)
    {
        $data = $this->initData($request);
        $orderNo = $data['order_no'];
        $loan = UserLoanRequest::with('userGlobalStatus')->byTransId($orderNo)->first();
        if(!$loan){
            return r360fail('借款信息不存在！');
        }
        $loan_amount = $data['loan_amount']; // 审批金额
        $loan_term = $data['loan_term']; // 审批期限
        $term_unit = $data['term_unit']; // 期限单位。1=天，2=月
        $loan->loan_money = intval($loan_amount * 100);
        $loan->period = $loan_term;
        $loan->save();
        $user = $this->orderNoToUser($orderNo);
        $fail_msg = $this->applyLoan($user, $request);
        if(is_string($fail_msg)){
            return r360fail($fail_msg);
        }
        return r360Success('', ['is_need_verify' => 0]);
    }

    /**
     * 放款
     * @param $user
     * @param $request
     * @return bool
     * @throws \App\Exceptions\GeneralException
     * @author cg
     * @date 2019-03-01 14:30
     */
    private function applyLoan($user, $request)
    {
        if (!UserGlobal::where('uid', $user->id)->where('global_status', UserGlobal::STATUS_LOAN_REQUEST_SUCCESS)->value('uid')) {
            return '当前用户状态不支持放款申请操作！';
        }
        //获取用户最新的一条授信成功id
        $loanRequest = UserLoanRequest::where('user_id', $user->id)
            ->where('status', UserLoanRequest::STATUS_SUCCESS)
            ->where('current', UserLoanRequest::CURRENT_NOW)
            ->select('id', 'user_id', 'channel', 'actually_loan_money', 'actually_period', 'credit_id', 'pre_insurance_amt')
            ->orderByDesc('id')
            ->first();
        if (!$loanRequest) {
            return '您尚未完成授信流程，无法执行当前操作';
        }
        // 检测授信数据是否已有放款操作
        $hasLoan = LoanApply::where('loan_request_id',$loanRequest->id)->value('id');
        if($hasLoan){
            return '当前授信已有放款申请操作';
        }
        //获取相关费率
        $getReplyRate = SettingRepayRate::getRateByChannl($loanRequest->channel, $loanRequest->actually_period);
        if (!$getReplyRate) {
            \Log::debug('手机号为' . $user->phone_num . '的用户于' . date('Y-m-d H:i:s') . '使用Ip地址为' . $request->getClientIp() . '的设备申请放款时，由于setting_replay_rates表中查询channel_code为(' . $loanRequest->channel . ')，period为（' . $loanRequest->actually_period . '）的数据信息不存在导致放款申请操作失败' . PHP_EOL);
            return '当前期数不可借款';
        }
        $cardInfo = UserBankCard::find($user->using_bank_card);
        if(!$cardInfo){
            return '未检测到您的收款银行卡，请您选择收款银行卡后重试';
        }
        $cardId = $cardInfo->id;
        $holdAgreementNum = $cardInfo->hold_agreement_num;

        $checkHoldAgreementNum = CommonPlatformRequestFacade::checkHoldAgreement($holdAgreementNum);
        if ($checkHoldAgreementNum['code'] !== '01') {
            return '申请放款失败，该银行卡不支持当前放款操作';
        }

        //发起放款申请
        $params = [
            'pre_insurance_amt' => doubleval($loanRequest->pre_insurance_amt / 100),
            'credit_id' => $loanRequest->credit_id,
            'amount' => doubleval($loanRequest->actually_loan_money / 100),
            'period' => $loanRequest->actually_period,
        ];
        $res = MoneyPlatformRequestFacade::applyLoan($params);
        \Log::debug('「 用户id为' . $user->id . '使用授信id为' . $loanRequest->credit_id . '银行卡id为' . $cardId . '进行放款申请时。资方放款返回值 」' . json_encode($res, JSON_UNESCAPED_UNICODE));
        if (empty($res) || empty($res['code'])) {
            return '请求失败，请重试';
        }
        if ($res['code'] !== '01') {
            return '申请放款失败，' . $res['message'];
        }
        $apply = new LoanApply();
        $apply->ip = $request->ip();
        $apply->loan_request_id = $loanRequest->id; //授信id
        $apply->user_id = $user->id;
        $apply->pre_insurance_amt = doubleval($loanRequest->pre_insurance_amt / 100);  //授信额度的前置险
        $apply->trans_money_list = '';  //分账明细
        $apply->bank_card_id = $cardId;  //申请放款的银行卡
        $apply->out_trade_id = !empty($res['data']['outTradeId']) ? $res['data']['outTradeId'] : '';
        $apply->amount = doubleval($loanRequest->actually_loan_money / 100);  //授信表中 申请的借款金额（未扣除前置险）
        $apply->period = $loanRequest->actually_period; //授信表中 申请的分期期限
        $apply->loan_sign = !empty($res['sign']) ? $res['sign'] : '';
        $apply->message = !empty($res['message']) ? $res['message'] : ''; //返回的信息
        $status = !empty($res['data']['status']) ? $res['data']['status'] : $res['subCode'];
        if (!$status) {
            \Log::debug('手机号为' . $user->phone_num . '的用户于' . date('Y-m-d H:i:s') . '使用Ip地址为' . $request->getClientIp() . '的设备申请放款时，对user_loan_requests表中id为' . $loanRequest->id . '的记录，向资方申请放款时资方响应信息中subcode字段和data.status字段都不存在导致此次放款申请操作失败' . PHP_EOL);
            return '申请放款失败，数据异常';
        }
        $apply->sub_code = $status;
        $apply->loan_status = LoanApply::getLoanStatusByRes($res);
        //费率配置
        foreach ($getReplyRate as $key => $value) {
            $apply->$key = $value;
        }
        $data = !empty($res['data']) ? $res['data'] : [];
        //新流订单id,还款时使用
        if (!empty($data['loanId'])) {
            $apply->loan_id = $data['loanId'];
        }
        //资方返回的分期数
        if (!empty($data['period'])) {
            $apply->period = $data['period'];
        }
        //资方放款的申请金额
        if (!empty($data['amount'])) {
            $apply->amount = $data['amount'];
        }

        if (!empty($data['loanTime'])) {
            $apply->loan_time = $data['loanTime'];
        }
        //资方返回的明细
        if (!empty($data['transMoneyList'])) {
            $apply->trans_money_list = $data['transMoneyList'];
            //获取放款明细详情
            $detail = LoanApply::getDetailByTransMoneyList($data['transMoneyList']);
            if ($detail['arrival_account']) {
                $apply->arrival_account = $detail['arrival_account'];
            }
            if ($detail['pre_insurance_amt']) {
                $apply->pre_insurance_amt = $detail['pre_insurance_amt'];
            }
            if ($detail['performance_insurance']) {
                $apply->performance_insurance = $detail['performance_insurance'];
            }
        }
        try {
            $apply->save();
        } catch (\Exception $e) {
            return \Log::debug('「申请放款时」 由于' . $e->getMessage() . '错误导致放款结果异常');
        }
        event(new UserLoanApplyEvent($apply));
        if ($apply->loan_status == LoanApply::LOAN_STATUS_PROCESSING) {
            //任务三分钟后加入队列处理，获取放款处理结果
            GetLoanResultJobQueue::dispatch($apply)->onQueue(QueueKey::QUEUE_GET_LOAN_RESULT)->delay(Carbon::now()->addMinutes(3));
        }
        return true;
    }



}
